#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace log_ns;

// 包装一个返回值为string，参数为string的函数指针
using func_t = std::function<std::string(std::string)>;

static const int gsockfd = -1;
static const uint16_t glocalport = 8888;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
};

// 继承一个禁止拷贝的基类。避免有人在栈上定义智能指针进行服务端拷贝
class UdpServer : public nocopy
{
public:
    UdpServer(func_t func, uint16_t localport = glocalport)
        : _sockfd(gsockfd),
          _localport(localport),
          _isrunning(false),
          _func(func)
    {
    }
    void InitServer()
    {
        // 1.创建socket文件
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd: %d\n", _sockfd);

        // 2.bind绑定
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local)); // 先把结构体清空
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport); // 端口号,主机序列转成网络序列
        // local.sin_addr.s_addr = inet_addr(_localip.c_str()); // 1.需要4字节ip地址 2.需要网络序列ip - 暂时
        local.sin_addr.s_addr = INADDR_ANY; // 服务器端进行任意ip地址绑定

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success\n");
    }
    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            // 3.服务器直接接收数据
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer), 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                inbuffer[n] = 0;
                std::cout << "[客户端:" << addr.Ip() << ":" << addr.Port() << "]# " << inbuffer << std::endl;

                // 把英文单词传入，让_func回调外部的，回调完后会返回
                std::string result = _func(inbuffer);

                // 4.再把这个回显字符串返回给客户端，客户端一定在peer里
                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }
    ~UdpServer()
    {
        if (_sockfd > gsockfd)
            ::close(_sockfd);
    }

private:
    int _sockfd;         // 文件描述符
    uint16_t _localport; // 服务端的端口号
    bool _isrunning;     // 服务端的运行状态

    func_t _func;
};